
import React, { Component, PropTypes } from 'react';
import { connect } from 'dva';
import { message, Modal, Pagination, Popconfirm, Button } from 'antd';
import styles from './../Users.css';
import moment from 'moment';
import Factory from '../../factory';
import * as datetime from '../../../utils/datetime'
import dataEditCreate from '../../addons/DataEdit'
import dataTableCreate from '../../addons/DataTable'
import DataEditTable from '../../addons/DataEditTable'
import * as menuService from '../../../services/menus';
import { deepEqual } from '../../../utils/objects';
import * as indiDiviService from '../../../services/AccountDivi';

const daoName = "COMP_TYYW_DIVI_FHQK";
const ButtonGroup = Button.Group;
const columns = [
  { title: '员工编号', width: 100, sorter: true, dataIndex: 'EMNO', key: 'EMNO', dispaly: true },
  { title: '员工姓名', width: 100, sorter: true, dataIndex: 'EMNM', key: 'EMNM', dispaly: true },
  { title: '所属机构', width: 100, sorter: true, dataIndex: 'UTNM', key: 'UTNM', dispaly: true },
  { title: '分成占比(%)', width: 100, sorter: true, dataIndex: 'DSVL', key: 'DSVL', dispaly: true },
];
const controls = [
  { name: "EMNO", label: "员工编号", type: "text", grid: 12 / 24, required: true },
  { name: "EMNM", label: "员工姓名", type: "text", grid: 12 / 24, required: true },
  { name: "UTNM", label: "所属机构", type: "text", grid: 12 / 24, required: true },
  { name: "Dsvl", label: "占比", type: "number", grid: 12 / 24, required: true },
] 
const EditFrom = dataEditCreate(daoName);
class COMP_TYYW_DIVI_FHQK extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataChange: false,
      searchData: {},
      diviDataSource: [],
      title: "",
      showEdit: false,
      isOK: 0
    };
  }
  componentWillReceiveProps(nextProps) {
    if ((!deepEqual(nextProps.jlid, this.props.jlid)) ||
      (!deepEqual(nextProps.ywid, this.props.ywid))) {
      this.loadData(nextProps.jlid, nextProps.ywid)
    }
  }
  componentDidMount() {
    this.loadData(this.props.jlid, this.props.ywid)
  }
  loadData(jlid, ywid) {
    let seeks = [];
    let whereItems = [];
    whereItems.push({
      FieldName: "JLID",
      Operator: "=",
      FieldValues: '' + jlid
    }, {
        FieldName: "YWID",
        Operator: "=",
        FieldValues: '' + ywid
      })
    seeks.push({
      WhereItems: whereItems,
      RelationSign: "AND"
    })
    this.state.diviDataSource = [];
    this.props.dispatch({
      type: `${daoName}/fetch`,
      payload: { daoName, seeks }
    });
  }
  searchHandle(data) {
    this.state.searchData = data
  }
  hideEditHandler() {
    this.props.dispatch({
      type: `${this.props.parentModel}/hideEdit`
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.setState({ diviDataSource: [] });
  }
  loadOptionData() {
    let options = []
    controls.map(c => {
      if (c.fetch) {
        let f = c.fetch;
        if (c.type === 'cascader-select') {
          f.isCascader = true;
        }
        if (c.type !== 'search') {
          options.push(f);
        }
      }
    })
    if (daoName && options.length > 0) {
      this.props.dispatch({ type: `${daoName}/fetchOptions`, payload: { options } });
    }
  }
  diviDel() {
    let keys = this.refs.table.getSelectedRowKeys();
    keys.sort();
    const datas = this.refs.table.state.datas;
    let indexs = [];
    const keyName = 'EMID'
    datas.map((d, k) => {
      for (let i = 0; i < keys.length; i++) {
        if (d[keyName] === keys[i]) {
          indexs.push(k)
        }
      }
    })
    if (indexs.length <= 0) {
      message.info('请选择删除的数据行！');
      return
    }
    let diviDsource = this.state.diviDataSource;
    if (diviDsource.length <= 0) {
      diviDsource = this.props.list;
    }
    for (let j = indexs.length - 1; j >= 0; j--) {
      const k = indexs[j]
      diviDsource.splice(k, 1)
    }
    this.setState({ diviDataSource: diviDsource })
  }
  diviSubmit() {
    const datas = this.refs.table.state.datas;
    let num = 0;
    if (datas.length <= 0) {
      num = this.state.isOK = 1
    }
    let jlid = this.props.jlid;
    let ywid = this.props.ywid;
    let dsvlSum = 0;
    let dataSource = []
    datas.map(d => {
      dsvlSum = dsvlSum + d.DSVL;
      let data = {
        YWID: Number(ywid),//承兑
        EMID: Number(d.EMID),
        DSVL: Number(d.DSVL) / 100
      }
      dataSource.push(data);
    })
    if (dsvlSum !== 100 && datas.length > 0) {
      message.info('占比和必须为100%');
      return;
    }
    let content = "";
    if (num === 0) {
      content = `你确认要认定给 ${datas.map(d => d.EMNM)} 吗？`
    } else {
      content = `你确认要删除认定吗？`
    }
    Modal.confirm({
      title: '提示',
      content: content,
      okText: '确定',
      cancelText: '取消',
      onOk: () => {
        indiDiviService.indiDiviQTZB({ num, jlid, ywid, dataSource }
        ).then(function (data) {
          if (data === 'OK') {
            message.success('保存认定成功！')
          } else {
            return;
          }
        }).catch(function (ex) {
          console.log('请求出错', ex)
        });
      }
    });
    const form = this.refs.diviForm.getForm();
    form.resetFields();
    this.props.dispatch({
      type: `${daoName}/setSelectedRowKeys`,
      payload: { selectedRowKeys: [] }
    });
  };
  DiviAdd() {
    let list = this.props
    const form = this.refs.diviForm.getForm();
    let isOK = true;
    let data = {};//空对象
    form.validateFields((err, values) => {
      if (!err) {
        if ((values.Dsvl === undefined || values.Dsvl === '') && (values.EmID === undefined || values.EmID === '')) {
          message.info('请输入认定信息！');
          isOK = false;
        } else if (values.Dsvl === undefined || values.Dsvl === '') {
          message.info('请输入分行值,且分户值不能>100%！');
          isOK = false;
        } else if (values.EmID === undefined || values.EmID === '') {
          message.info('请输入员工信息！');
          isOK = false;
        } else {
          data.DSVL = Number(values.Dsvl);
        }
      }
    });
    if (!isOK) {
      return;
    }
    if (this.state.searchData.ID < 0 || this.state.searchData.No.indexOf(":") > 0) {
      message.error('分配失败！员工：' + this.state.searchData.Name + '为虚拟员工，不支持业绩分配！请重新选择')
      return;
    }
    data.EMID = this.state.searchData.ID;             //员工ID
    data.EMNO = this.state.searchData.No;             //员工编号
    data.EMNM = this.state.searchData.Name;           //员工名称
    data.UTNM = this.state.searchData.Organization.Name;//开户机构
    let diviSum = data.DSVL;                          //判断一下占比是否大于100
    let diviDs = this.state.diviDataSource
    diviDs.map(d => diviSum += d.DSVL)
    if (diviSum > 100) {
      message.info('分户值不能大于100%！');
      return;
    } else {
      diviDs.push(data);
      this.setState({ diviDataSource: diviDs });
    }
  }
  render() {
    let { list } = this.props
    list = this.state.diviDataSource.length <= 0 ? list : this.state.diviDataSource;
    const controlsFilter = [
      {
        name: "EmID", label: "员工", type: "search", grid: 6 / 24, required: false,
        dataType: "number", fetch: { daoName: "UserSel", searchColumns: ['No', 'Name'], optionTpl: 'Name', valueTpl: "ID", onSelect: this.searchHandle.bind(this) },
        layout: { labelSpan: 7, wrapperSpan: 17 }
      }, {
        name: "Dsvl", label: "占比%", type: "input-number", grid: 7 / 24, dataType: "number",
        layout: { labelSpan: 7, wrapperSpan: 15 }
      }, {
        name: 'XS', required: false, type: 'button-group',
        data: [{ value: '1', label: '新增', onClick: this.DiviAdd.bind(this) }, { value: '2', label: '删除', onClick: this.diviDel.bind(this) }],
        grid: 10 / 24, layout: { labelSpan: 7, wrapperSpan: 15 }
      },
    ];
    return (
      <Modal title={this.props.title} okText={"保存"} width={700} visible={this.props.showEdit} onCancel={this.hideEditHandler.bind(this)} onOk={this.diviSubmit.bind(this)} >
        <div className={styles.normal} style={{ background: '#fff', marginTop: -16, padding: '5px 5px' }}>
          <div>
            <div className={styles.create}>
              <EditFrom ref="diviForm" daoName={daoName} controls={controlsFilter} clearItemMargin={true} selectFirst={false} />
            </div>
            <DataEditTable ref="table" columns={columns} controls={controls} footer={true} dataSource={list}  multiSelect={true} keyName={"EMID"} />
          </div>
        </div>
      </Modal>
    )
  }

}

COMP_TYYW_DIVI_FHQK.propTypes = {
  ywid: PropTypes.number,
  jlid: PropTypes.number,
  showEdit: PropTypes.bool,
  title: PropTypes.string,
  parentModel: PropTypes.string


};
COMP_TYYW_DIVI_FHQK.defaultProps = {
  ywid: -1,
  jlid: -1,
  showEdit: false,
  title: "",
  parentModel: ""
};

function mapStateToProps(state) {
  const { list } = state[daoName];
  return {
    list
  }
}
COMP_TYYW_DIVI_FHQK = connect(mapStateToProps)(COMP_TYYW_DIVI_FHQK)
export default COMP_TYYW_DIVI_FHQK;
